package com.yunwei.activity;

import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.squareup.okhttp.OkHttpClient;
import com.yunwei.BaseApplication;
import com.yunwei.R;
import com.yunwei.dao.Note;
import com.yunwei.dao.NoteDao;
import com.yunwei.http.MyOkHttpInterceptor;
import com.yunwei.http.UserService;
import com.yunwei.service.NoteService;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;

import retrofit.Retrofit;

/**
 * Created by weijianxing on 9/16/15.
 */
public class NoteActivity extends ListActivity {


    private NoteService noteService;

    private List<Note> noteList;

    private NoteDao noteDao;

    private EditText editText;

    private Cursor cursor;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /**
         * http://stackoverflow.com/questions/29884967/how-to-dynamically-set-headers-in-retrofit-android
         *
         * 自定义的request
         */
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.networkInterceptors().add(new MyOkHttpInterceptor());

        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://192.168.1.9:8081/api").client(okHttpClient).build();

        UserService userService = retrofit.create(UserService.class);

        userService.listUsers();
        setContentView(R.layout.activity_main);

        noteDao = BaseApplication.getNoteDao(this);

        noteService = BaseApplication.getNoteService(getBaseContext());

        SQLiteDatabase db = noteDao.getDatabase();

        Cursor cursor = db.query(NoteDao.TABLENAME, noteDao.getAllColumns(), null, null, null, null, null);

        String textColumn = NoteDao.Properties.Text.columnName;
        String[] from = {textColumn, NoteDao.Properties.Comment.columnName};
        int[] to = {android.R.id.text1, android.R.id.text2};

        noteList = noteService.findAllNote();

        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, from,
                to);

        setListAdapter(adapter);

        editText = (EditText) findViewById(R.id.editTextNote);

    }

    protected void addUiListeners() {
        editText.setOnEditorActionListener(new OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    addNote();
                    return true;
                }
                return false;
            }
        });

        final View button = findViewById(R.id.buttonAdd);
        button.setEnabled(false);
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                boolean enable = s.length() != 0;
                button.setEnabled(enable);
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    public void onMyButtonClick(View view) {
        addNote();
    }

    private void addNote() {
        String noteText = editText.getText().toString();
        editText.setText("");

        final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
        String comment = "Added on " + df.format(new Date());
        Note note = new Note(null, noteText, comment, new Date());
        noteDao.insert(note);
        Log.d("DaoExample", "Inserted new note, ID: " + note.getId());

        cursor.requery();
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        noteDao.deleteByKey(id);
        Log.d("DaoExample", "Deleted note, ID: " + id);
        cursor.requery();
    }
}
